package com.yulp.springboot2task.job;

/**
 * @description:
 * @date: 2019/11/6 11:05.
 * @author: yulipeng.
 */
import com.yulp.springboot2task.utils.DateUtil;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 定时异步通知
 * Created by yulipeng on 2017/8/24.
 *
 * 可以作废
 */
public class NotifyQuartzJob implements Job {

    private static final Logger logger = LoggerFactory.getLogger(NotifyQuartzJob.class);

    public void init() {
        //获取spring的bean
    }

    public static AtomicInteger atomicInteger = new AtomicInteger(0);
    public static ConcurrentHashMap map = new ConcurrentHashMap();

    @Override
    public void execute(JobExecutionContext context) {
        //init();
        logger.info(DateUtil.currentDateLong()+ ": Quartz-job开始执行=========>"+atomicInteger.get());
        atomicInteger.getAndIncrement();

        //TriggerKey trkey = context.getTrigger().getKey();

        JobDataMap dataMap = context.getMergedJobDataMap();
        String jobType = dataMap.getString("jobType");
        String orderNo = dataMap.getString("orderNo");
        System.out.println("orderNo:" + orderNo + "; jobType:" + jobType);

        Integer value;
        if (map.containsKey(jobType)) {
            value = Integer.parseInt(map.get(jobType).toString());
        } else {
            value = Integer.parseInt(orderNo);
        }
        map.put(jobType, value + 1);

        // 1.数据库查询通知信息，是否需要执行任务（考虑使用分布式锁处理）
        // mapper.select();.....
        if ("123".equals(orderNo)) {
            //System.out.println("停止调度:" + orderNo);
            //unscheduleJob(context, trkey);
            //return;
        }

        // 2.发送通知-再次执行业务
        // http接口....

        // 3. 根据接口返回状态判断是否要停止任务；
        if (value > 9) {
            System.out.println(DateUtil.currentDateLong()+ ": 停止调度:" + "orderNo:" + orderNo + "; jobType:" + jobType);
            unscheduleJob(context);
        }

        //4.更新通知状态和发送次数
        // mapper.updateNotityTableStatus
    }

    /**
     * 停止调度Job任务
     *
     * @param context
     */
    public void unscheduleJob(JobExecutionContext context) {
        try {
            System.out.println("停止调度任务.....");
            //context.getScheduler().unscheduleJob(trKey);

            JobKey jobKey = context.getJobDetail().getKey();
            TriggerKey triggerKey = context.getTrigger().getKey();

            // 停止触发器
            context.getScheduler().pauseTrigger(triggerKey);
            // 移除触发器
            context.getScheduler().unscheduleJob(triggerKey);
            // 删除任务
            context.getScheduler().deleteJob(jobKey); // JobKey.jobKey(jobName, jobGroupName)
        } catch (SchedulerException e) {
            logger.error("停止调度job异常:" + e.getMessage(), e);
        }
    }
}
